//
//  StepCountViewController.m
//  记步-Demo
//
//  Created by qinlongqing on 14/11/11.
//  Copyright (c) 2014年 qinlongqing. All rights reserved.
//

#import "StepCountViewController.h"
#import "MotionAndLocationManager.h"
#import "sys/utsname.h"
#import "StepsCountListTableViewCell.h"
//#import "StepsCountSetViewController.h"
#import "BeforOrAfterDayCalculate.h"
#import "StepsCountShareViewController.h"
#import "AppConfig.h"
#import "CLDataBaseController.h"

#define kFromDateStringKey    @"fromDateStringKey"
#define kToDateStringKey      @"toDateStringKey"
#define kStepsInAnHourKey     @"stepsNumberKey"


@interface StepCountViewController ()<MotionAndLocationManagerDelegate,UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSMutableDictionary *allHourAndStepsInDict;//用于存储一天之内所有的小时
    NSArray *allKeys;//存储排好序的时间,从00--23排序
    
    BOOL isQueryPedometerData;//标记当前是否在查询 M7
    NSMutableArray *queryedPedometerDataArray;//查询出来的结果
    NSInteger getQueryCount;//用于标记获取到的查询结果
    
    NSDate *currentShowDateStart;//当前显示的那一天
    
    UIBarButtonItem *shareBtnImg;//分享按钮,提交完数据后才能点击
    
    NSString *todayString;//今天日期的字符串
    NSUInteger todayAllSteps;//今天所有的步数
}
@end

@implementation StepCountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorFromRGB(0x4fc1e9);
    
    self.goToRightBTN.hidden = YES;
    currentShowDateStart = [NSDate date];//第一次显示的是当天
    
    allHourAndStepsInDict = [[NSMutableDictionary alloc] init];
    
    queryedPedometerDataArray = [[NSMutableArray alloc]init];
    getQueryCount = 0;
    
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        [self initUserDefaultForDay];//初始化userDefault所存记步数据
    }

//    [self setUserInfo];
    [self makeNavBar];
    [self createAndSetStepsListView];
    [self setCurrentDateLabel];
#pragma 方法一
//    if ([self isM7ActivityAvailable]) {//iPhone5s以上的机器可用
//        if ([HKHealthStore isHealthDataAvailable]) {
//            HKHealthStore *store = [[HKHealthStore alloc]init];
//            [store requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]] completion:^(BOOL success, NSError *error) {
//                if (success) {
//                    NSLog(@"---yes--%d",success);
//                    [MotionAndLocationManager sharedInstance].isM7Support = YES;
//                    [[MotionAndLocationManager sharedInstance] start];
//                    [MotionAndLocationManager sharedInstance].delegate = self;
//                    
//                    [self uploadUserStepsTodayForM7];//上传今天所有的步数
//                }
//                else{
//                    NSLog(@"---no--%d",success);
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"健康数据不可用,请在 设置->安好 中开启允许访问运动记录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                        [alertView show];
//                    });
//                }
//            }];
//        }
//    }
#pragma 方法二
    if ([self isM7ActivityAvailable]) {//iPhone5s以上的机器可用
        if ([[MotionAndLocationManager sharedInstance] isM7StepsDataAvailable]) {
            [MotionAndLocationManager sharedInstance].isM7Support = YES;
            [[MotionAndLocationManager sharedInstance] start];
            [MotionAndLocationManager sharedInstance].delegate = self;
        
            if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
                [self uploadUserStepsTodayForM7];//上传今天所有的步数
            }
        }
        else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"健康数据不可用,请在 设置->安好 中开启允许访问运动记录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
    else{
        if ([[MotionAndLocationManager sharedInstance] isLocationAvailable]) {
//#ifdef debug
//            NSString *accFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"accLog.xml"];
//            NSString *locationFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"locationLog.xml"];
//            
//            NSFileManager *fm = [NSFileManager defaultManager];
//            if ([fm fileExistsAtPath:accFilePath]) {
//                [fm removeItemAtPath:accFilePath error:nil];
//            }
//            if ([fm fileExistsAtPath:locationFilePath]) {
//                [fm removeItemAtPath:locationFilePath error:nil];
//            }
//#endif
            
            [MotionAndLocationManager sharedInstance].isM7Support = NO;
            [[MotionAndLocationManager sharedInstance] start];
            [MotionAndLocationManager sharedInstance].delegate = self;
            
            if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
                [self uploadUserStepsTodayForLocationAndMotion];//上传今天所有的步数
            }
        }
        else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位或加速器不可用,请在设置->隐私->定位服务中设置" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
    
    //添加滑动事件
    UISwipeGestureRecognizer *leftSwip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doLeftSwipe)];
    leftSwip.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:leftSwip];
    
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doRightSwipe)];
    rightSwip.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwip];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self backBtnclicked];
    }
}

- (void)uploadUserStepsTodayForM7{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *yyyyMMdd = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:8];
    [[MotionAndLocationManager sharedInstance] getAllStepsForDay:yyyyMMdd];//这个通过代理回调返回所有的步数
}
- (void)didGetAllSteps:(NSUInteger)allSteps forDay:(NSString *)yyyyMMdd{
    todayAllSteps = allSteps;
    todayString = yyyyMMdd;

    if (allSteps > 0 && [[CLDataBaseController instance] selectToGetUserDefaultStoredAllStepsForDay] < allSteps) {//所计步数>0、存的是今天、两次步数有变化
        [self doUploadAllSteps:allSteps];
    }
}

- (void)uploadUserStepsTodayForLocationAndMotion{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *yyyyMMdd = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:8];
    NSUInteger allSteps = [[MotionAndLocationManager sharedInstance] getAllStepsForDay:yyyyMMdd];//这个直接返回所有的步数

    todayAllSteps = allSteps;
    todayString = yyyyMMdd;

    if (allSteps > 0 && [[CLDataBaseController instance] selectToGetUserDefaultStoredAllStepsForDay] < allSteps) {//所计步数>0、存的是今天、两次步数有变化
        [self doUploadAllSteps:allSteps];
    }
}

- (void)initUserDefaultForDay{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *yyyyMMdd = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:8];
    
    if ([[[CLDataBaseController instance] selectToGetUserDefaultStoredDay] isEqualToString:@""]) {//不存在所登用户的数据
        [[CLDataBaseController instance] insertStepCountUploadForDay:yyyyMMdd andDayAllSteps:0];
    }
    else if (![[[CLDataBaseController instance] selectToGetUserDefaultStoredDay] isEqualToString:yyyyMMdd]){
        [[CLDataBaseController instance] updataStepCountUploadForDay:yyyyMMdd andDayAllSteps:0];
    }
}


- (void)doUploadAllSteps:(NSUInteger)allSteps{
    //判断是否登录,如果已登录：直接存入服务器。如果未登录：存入本地
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"total":[NSString stringWithFormat:@"%ld",allSteps],@"daytime":[self setNewTime]};
        
        [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kUploadJiBuURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber * statusNum = [responseObject objectForKey:@"status"];
            NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
            NSString * statusString = [numberFormatter stringFromNumber:statusNum];
            if ([statusString isEqualToString:@"0"]) {
                MyNSLog("----%@",[responseObject valueForKey:@"msg"]);
            }else{
                NSLog(@"上传成功");
                shareBtnImg.enabled = YES;
                
                [[CLDataBaseController instance] updataStepCountUploadForDay:todayString andDayAllSteps:todayAllSteps];//每次上传成功以后再设置userDefault
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        }];
    }
    else{//未登录

    }
}

- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}


//- (void)setUserInfo{
//    self.userInfoView.alpha = 0.3;
//    self.userPhotoImageView.layer.cornerRadius = 2;
//    self.userPhotoImageView.clipsToBounds = YES;
//    
//    if ([NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]].length > 0) {//登录
//        [self.userPhotoImageView setImageWithURL:[NSURL URLWithString:[[UserManager shareInstance] getUserInfo].avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
//        self.userNameLabel.text = [[UserManager shareInstance] getUserInfo].username;
//    }
//    else{//未登录
//        self.userPhotoImageView.image = [UIImage imageNamed:@"默认头像"];
//        self.userNameLabel.text = @"未登录";
//    }
//}

-(void)makeNavBar{
    self.navigationItem.title = @"记步提醒";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    shareBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_分享"] style:UIBarButtonItemStylePlain target:self action:@selector(shareBtnClicked)];
    shareBtnImg.tintColor = [UIColor whiteColor];
    shareBtnImg.enabled = NO;
    self.navigationItem.rightBarButtonItem = shareBtnImg;
}

-(void)backBtnclicked{
    [MotionAndLocationManager deallocInstance];
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)shareBtnClicked{
    StepsCountShareViewController *shareViewController;
    if (kScreenWidth == 414) {
        shareViewController = [[StepsCountShareViewController alloc]initWithNibName:@"StepsCountShareViewController_6+" bundle:nil];
    }
    else{
        shareViewController = [[StepsCountShareViewController alloc]initWithNibName:@"StepsCountShareViewController" bundle:nil];
    }
    shareViewController.totalSteps = [self.currentStepsLabel.text integerValue];
    shareViewController.dateString = self.currentTimeLabel.text;
    [self.navigationController pushViewController:shareViewController animated:YES];
}

- (void)motionAndLocationManagerUpdataCurrentStepsDetailFrom_M7:(MotionAndLocationManager *)motionAndLocationManager{
    if ([self isShowingToday]) {
        if (isQueryPedometerData == NO) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *yyyyMMdd = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:8];
            [self getAllHoursWithCurrentDate:yyyyMMdd];
            
            isQueryPedometerData = YES;//标记为正在查询,当24小时全部查询完以后，在标记为NO
            [queryedPedometerDataArray removeAllObjects];//把以前查询的结果删除
            getQueryCount = 0;//从新标记为0
            [self startQueryAllStepsIn24Hour_M7];//开始查询
        }
    }
}

- (void)startQueryAllStepsIn24Hour_M7{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    for (NSInteger i=0; i<allHourAndStepsInDict.allKeys.count; i++) {
        NSString *hourKey = nil;
        if (i<10) {
            hourKey = [NSString stringWithFormat:@"0%ld",i];
        }
        else{
            hourKey = [NSString stringWithFormat:@"%ld",i];
        }
        NSDictionary *thisDict = [allHourAndStepsInDict objectForKey:hourKey];
        NSDate *fromDate = [dateFormatter dateFromString:[thisDict valueForKey:kFromDateStringKey]];
        NSDate *toDate = [dateFormatter dateFromString:[thisDict valueForKey:kToDateStringKey]];
        
        [[[MotionAndLocationManager sharedInstance] getStepFromDate:fromDate toDate:toDate] integerValue];
    }
}

- (void)motionAndLocationManagerGetPedometerDataInAnHour:(CMPedometerData *)pedometerData{
    getQueryCount += 1;
    if (pedometerData != nil) {
        [queryedPedometerDataArray addObject:pedometerData];
    }
    if (getQueryCount == 24) {
        NSInteger totalSteps = 0;

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        for (NSInteger i=0; i<queryedPedometerDataArray.count; i++) {
            NSDate *startDate = ((CMPedometerData *)[queryedPedometerDataArray objectAtIndex:i]).startDate;
            NSInteger numberOfSteps = [((CMPedometerData *)[queryedPedometerDataArray objectAtIndex:i]).numberOfSteps integerValue];
            
            NSString *startDateString = [dateFormatter stringFromDate:startDate];
            NSString *HH = [startDateString substringWithRange:NSMakeRange(8, 2)];
            if (numberOfSteps > 0) {//在这个小时内有记步
                [[allHourAndStepsInDict valueForKey:HH] setValue:[NSNumber numberWithInteger:numberOfSteps] forKey:kStepsInAnHourKey];
                totalSteps += numberOfSteps;
            }
        }
        //删除记步为0的时间段
        NSMutableArray *allRemoveKeys = [[NSMutableArray alloc]init];
        for (NSInteger i=0; i<24; i++) {
            NSString *hourKey = nil;
            if (i<10) {
                hourKey = [NSString stringWithFormat:@"0%ld",i];
            }
            else{
                hourKey = [NSString stringWithFormat:@"%ld",i];
            }
            NSMutableDictionary *dict = [allHourAndStepsInDict valueForKey:hourKey];
            if ([[dict valueForKey:kStepsInAnHourKey] integerValue] <= 0) {
                [allRemoveKeys addObject:hourKey];
            }
        }
        [allHourAndStepsInDict removeObjectsForKeys:allRemoveKeys];
        
        //更新界面
        self.currentStepsLabel.text = [NSString stringWithFormat:@"%ld",totalSteps];
        if (self.currentStepsLabel.text.length > 4) {
            CGFloat size = 92 - (self.currentStepsLabel.text.length - 4)*13;
            [self.currentStepsLabel setFont:[UIFont systemFontOfSize:size]];
        }
        [self setCurrentDateLabel];
        
        if (totalSteps > 0) {
            [UIView animateWithDuration:0.3 animations:^{
                CGRect rect = self.myTabelView.frame;
                rect.origin.y = kScreenHeight - 64 - rect.size.height;
                self.myTabelView.frame = rect;
            }];
        }
        else{
            if (totalSteps == 0) {
                [UIView animateWithDuration:0.3 animations:^{
                    CGRect rect = self.myTabelView.frame;
                    rect.origin.y = kScreenHeight - 64;
                    self.myTabelView.frame = rect;
                }];
            }
        }
        
        allKeys = [allHourAndStepsInDict allKeys];
//        NSLog(@"111M7=%@",allKeys);
        allKeys = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] < [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        }];

//        NSLog(@"222M7=%@",allKeys);
        [self.myTabelView reloadData];

        isQueryPedometerData = NO;//标记为NO，表示可以继续查询
    }
}

- (void)motionAndLocationManager:(MotionAndLocationManager *)motionAndLocationManager updataCurrentStepsDetailFrom_DB:(NSMutableArray *)stepsDetail{
    if ([self isShowingToday]) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *yyyyMMdd = [[dateFormatter stringFromDate:[NSDate date]] substringToIndex:8];
        [self loadStepsBeforeInData:yyyyMMdd withAllStepsData:stepsDetail];
    }
}

/**
 *  把一天之内的所有步数按小时划分，算出每个小时内走的步数
 *
 *  @param yyyyMMdd 具体某一天需要划分
 *  @param allSteps 所有的步数信息
 */
- (void)loadStepsBeforeInData:(NSString *)yyyyMMdd withAllStepsData:(NSMutableArray *)allSteps{
    if (yyyyMMdd == nil) {
        return;
    }
    [self getAllHoursWithCurrentDate:yyyyMMdd];
    
    NSInteger totalSteps = 0;
    
    //把所有的数据归类
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    for (NSInteger i=0; i<allSteps.count; i++) {
        NSDictionary *thisDict = [allSteps objectAtIndex:i];
        NSString *thisDateString = [dateFormatter stringFromDate:[thisDict valueForKey:kTimeForCurrentStep]];
        NSString *thisyyyyMMdd = [thisDateString substringToIndex:8];
        if ([thisyyyyMMdd isEqualToString:yyyyMMdd]) {
            NSString *HH = [thisDateString substringWithRange:NSMakeRange(8, 2)];
            NSMutableDictionary *thisHourDict = [allHourAndStepsInDict valueForKey:HH];
            NSInteger currentStepsInThisHour = [[thisHourDict valueForKey:kStepsInAnHourKey] integerValue];
            [thisHourDict setValue:[NSNumber numberWithInteger:(currentStepsInThisHour + 1)] forKey:kStepsInAnHourKey];
            totalSteps += 1;
        }
    }
    
    self.currentStepsLabel.text = [NSString stringWithFormat:@"%ld",totalSteps];
    if (self.currentStepsLabel.text.length > 4) {
        CGFloat size = 92 - (self.currentStepsLabel.text.length - 4)*13;
        [self.currentStepsLabel setFont:[UIFont systemFontOfSize:size]];
    }
    [self setCurrentDateLabel];
    
    if (totalSteps > 0) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect rect = self.myTabelView.frame;
            rect.origin.y = kScreenHeight - 64 - rect.size.height;
            self.myTabelView.frame = rect;
        }];
    }
    else{
        if (totalSteps == 0) {
            [UIView animateWithDuration:0.3 animations:^{
                CGRect rect = self.myTabelView.frame;
                rect.origin.y = kScreenHeight - 64;
                self.myTabelView.frame = rect;
            }];
        }
    }
    
    NSMutableArray *allRemoveKeys = [[NSMutableArray alloc]init];
    for (NSInteger j=0; j<allHourAndStepsInDict.count; j++) {
        NSString *hourKey = nil;
        if (j<10) {
            hourKey = [NSString stringWithFormat:@"0%ld",j];
        }
        else{
            hourKey = [NSString stringWithFormat:@"%ld",j];
        }
        NSDictionary *thisDict = [allHourAndStepsInDict valueForKey:hourKey];
        if ([[thisDict valueForKey:kStepsInAnHourKey] integerValue] == 0) {
            [allRemoveKeys addObject:hourKey];
        }
    }
    [allHourAndStepsInDict removeObjectsForKeys:allRemoveKeys];
    
    allKeys = [allHourAndStepsInDict allKeys];
//    NSLog(@"111=%@",allKeys);
    allKeys = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
//    NSLog(@"222=%@",allKeys);
    [self.myTabelView reloadData];
}

- (void)getAllHoursWithCurrentDate:(NSString *)yyyyMMdd{
    [allHourAndStepsInDict removeAllObjects];
    NSString *fromDateString;
    NSString *toDateString;
    for (NSInteger i=0; i<24; i++) {
        if (i<10) {
            fromDateString = [yyyyMMdd stringByAppendingFormat:@"0%ld0000",i];
        }
        else{
            fromDateString = [yyyyMMdd stringByAppendingFormat:@"%ld0000",i];
        }
        if (i<10) {
            toDateString = [yyyyMMdd stringByAppendingFormat:@"0%ld5959",i];
        }
        else{
            toDateString = [yyyyMMdd stringByAppendingFormat:@"%ld5959",i];
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:fromDateString,kFromDateStringKey,toDateString,kToDateStringKey,[NSNumber numberWithInteger:0],kStepsInAnHourKey, nil];
        NSString *hourKey = nil;
        if (i<10) {
            hourKey = [NSString stringWithFormat:@"0%ld",i];
        }
        else{
            hourKey = [NSString stringWithFormat:@"%ld",i];
        }
        [allHourAndStepsInDict setObject:dict forKey:hourKey];
    }
}

- (void)setCurrentDateLabel{//创建显示走了多少步的view
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    self.currentTimeLabel.text = [[dateFormatter stringFromDate:currentShowDateStart] substringToIndex:11];
}

- (void)createAndSetStepsListView{//创建显示每个小时走了多少步的view
    self.myTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTabelView.backgroundColor = [UIColor clearColor];
    self.myTabelView.showsVerticalScrollIndicator = YES;
    self.myTabelView.showsHorizontalScrollIndicator = YES;
    
    CGRect rect = self.myTabelView.frame;
    rect.origin.y = kScreenHeight - 64;
    self.myTabelView.frame = rect;
}

#pragma UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return allHourAndStepsInDict.allKeys.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 160;
    }
    else{
        return 134;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"stepsCountCell";
    StepsCountListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"StepsCountListTableViewCell" owner:self options:nil] lastObject];
        }
        else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"StepsCountListTableViewCell" owner:self options:nil] firstObject];
        }
    }
    
    NSMutableDictionary *currentCellDict = [allHourAndStepsInDict valueForKey:[allKeys objectAtIndex:indexPath.row]];
    if (currentCellDict) {
        cell.fromTimeLabel.text = [self getHHmm:[currentCellDict valueForKey:kFromDateStringKey]];
        cell.toTimeLabel.text = [self getHHmm:[currentCellDict valueForKey:kToDateStringKey]];
        cell.stepsInThisTimeLabel.text = [NSString stringWithFormat:@"%ld",[[currentCellDict valueForKey:kStepsInAnHourKey] integerValue]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.upDividerView.hidden = NO;
    cell.bottomDividerView.hidden = NO;
    if (indexPath.row == 0) {
        cell.upDividerView.hidden = YES;
    }
    if (indexPath.row == [allHourAndStepsInDict.allKeys count] - 1) {
        cell.bottomDividerView.hidden = YES;
    }
    return cell;
}

- (NSString *)getHHmm:(NSString *)time{
    NSString *hh = [time substringWithRange:NSMakeRange(8, 2)];
    NSString *mm = [time substringWithRange:NSMakeRange(10, 2)];
    
    return [NSString stringWithFormat:@"%@:%@",hh,mm];
}

- (BOOL)isM7ActivityAvailable{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone3,1"]){//iphone4
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone4,1"]){//iphone4s
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone5,1"]){//iphone5
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone5,2"]){//iphone5
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone5,3"]){//iphone5c
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone5,4"]){//iphone5c
        return NO;
    }
    else if ([deviceString isEqualToString:@"iPhone6,1"]){//iphone5s
        if (IOS8_OR_LATER) {
            return YES;
        }
        else{
            return NO;
        }
//        return NO;//测试用、不用M7
    }
    else if ([deviceString isEqualToString:@"iPhone6,2"]){//iphone5s
        if (IOS8_OR_LATER) {
            return YES;
        }
        else{
            return NO;
        }
//        return NO;//测试用、不用M7
    }
    else if ([deviceString isEqualToString:@"iPhone7,2"]){//iphone6
        if (IOS8_OR_LATER) {
            return YES;
        }
        else{
            return NO;
        }
//        return NO;//测试用、不用M7
    }
    else if ([deviceString isEqualToString:@"iPhone7,1"]){//iphone6 plus
        if (IOS8_OR_LATER) {
            return YES;
        }
        else{
            return NO;
        }
//        return NO;//测试用、不用M7
    }
    else if ([deviceString isEqualToString:@"i386"]){
        return NO;
    }
    else if ([deviceString isEqualToString:@"x86_64"]){
        return NO;
    }
    
    return NO;
}


//- (IBAction)doPushSetView:(id)sender {
//    StepsCountSetViewController *setViewController = [[StepsCountSetViewController alloc]init];
//    [self.navigationController pushViewController:setViewController animated:YES];
//}


#pragma 滑动事件关联方法
- (void)doLeftSwipe{//向左滑动
    [self doGoToRightBTN:nil];
}

- (void)doRightSwipe{//向右滑动
    [self doGoToLeftBTN:nil];
}


- (IBAction)doGoToLeftBTN:(id)sender {
    currentShowDateStart = [NSDate dateWithTimeIntervalSince1970:[BeforOrAfterDayCalculate preDayOfTheDate_start:currentShowDateStart]];
    self.goToRightBTN.hidden = NO;
    
    [self setCurrentDateLabel];
    
    [self showAllDataForCurrentShowingDay];
}

- (IBAction)doGoToRightBTN:(id)sender {
    if (![self isShowingToday]) {
        currentShowDateStart = [NSDate dateWithTimeIntervalSince1970:[BeforOrAfterDayCalculate nextDayOfTheDate_start:currentShowDateStart]];
        [self setCurrentDateLabel];
        if ([self isShowingToday]) {
            self.goToRightBTN.hidden = YES;
        }
        
        [self showAllDataForCurrentShowingDay];
    }
}

#pragma 得到某一天的所有数据
- (void)showAllDataForCurrentShowingDay{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *yyyyMMdd = [[dateFormatter stringFromDate:currentShowDateStart] substringToIndex:8];
    if ([self isM7ActivityAvailable]) {//iPhone5s以上的机器
        if (isQueryPedometerData == NO) {
            [self getAllHoursWithCurrentDate:yyyyMMdd];
            
            isQueryPedometerData = YES;//标记为正在查询,当24小时全部查询完以后，在标记为NO
            [queryedPedometerDataArray removeAllObjects];//把以前查询的结果删除
            getQueryCount = 0;//从新标记为0
            [self startQueryAllStepsIn24Hour_M7];//开始查询
        }
    }
    else{
        NSString *yyyyMMdd = [[dateFormatter stringFromDate:currentShowDateStart] substringToIndex:8];
        NSString *fromDateString = [yyyyMMdd stringByAppendingFormat:@"000000"];
        NSString *toDateString = [yyyyMMdd stringByAppendingFormat:@"235959"];
        NSDate *fromDate = [dateFormatter dateFromString:fromDateString];
        NSDate *toDate = [dateFormatter dateFromString:toDateString];
        NSMutableArray *allStepsInThisDayArray = [[[MotionAndLocationManager sharedInstance] getStepFromDate:fromDate toDate:toDate] mutableCopy];

        [self loadStepsBeforeInData:yyyyMMdd withAllStepsData:allStepsInThisDayArray];
    }
}

- (BOOL)isShowingToday{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    BOOL isShowingToday = [[dateFormatter stringFromDate:[NSDate date]] isEqualToString:[dateFormatter stringFromDate:currentShowDateStart]];
    if (isShowingToday == YES) {
        self.goToRightBTN.hidden = YES;
    }
    else{
        self.goToRightBTN.hidden = NO;
    }
    return isShowingToday;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
